﻿using System;
using Microsoft.Exchange.WebServices.Data;
using MailClient;
using MailClient.Mail;

namespace MailClient.Queue
{

	/// <summary>
	/// checks for and marshalls new mail asynchrously
	/// </summary>
	public class IncomingRunner
	{
		#region Private Declarations

		private MailMessage _msg;
		private TimeSpan _time;
		private MessageEventArgs Margs;
		private SwitchBoard SqlTraffic;

		#endregion
		public delegate void CommandCompleteHandler(MessageEventArgs e);
		public event CommandCompleteHandler CommandComplete;

		#region Ctor

		public IncomingRunner(MailMessage msg)
		{
			_msg = msg;
			SqlTraffic = new SwitchBoard (msg);
			SqlTraffic.CommandComplete += new SwitchBoard.CommandCompleteHandler(SqlTraffic_CommandComplete);
		}

		public IncomingRunner(MailMessage msg, TimeSpan time) :
			this(msg)
		{
			_time = time;
		}

		#endregion

		#region Public Methods

		public void Process ()
		{
			// figure out the sender and see if they sent something recently

			// SEND MSG TO SPAM DETECTOR
			/*
			 * need to make a pre-processor so that emails
			 * having the word Training as the first word of
			 * the subject will circumvent this filter
			 */

			Handlers.spamdetect IsPork = new Handlers.spamdetect (_msg.Subject, _msg.Body);
			lock (IsPork) {
				if (IsPork.TestMail ()) {
					Margs = new MessageEventArgs (_msg, "This message is Spam");
				} else {
					
					Margs = new MessageEventArgs(_msg, "Not Spam");
					SqlTraffic.Process ();
				}
			}
			if (CommandComplete != null)
				CommandComplete(Margs);
		}

		#endregion
		
		#region Private Methods
		void SqlTraffic_CommandComplete(MessageEventArgs e)
		{
			Handlers.incoming inbound = new Handlers.incoming(_msg);
			MailMessage ReplyEmail = inbound.Process();
			//_client.MoveMessage(_msg.Uid, "INBOX/ToFile");
		}
		#endregion

	}
}
